package de.traveltainment.concept.envers.repository;

import de.traveltainment.concept.envers.database.Constants;
import de.traveltainment.concept.envers.entities.ChangeType;
import de.traveltainment.concept.envers.entities.Vito;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.Calendar;
import java.util.List;

/**
 * Created by borlis on 13.06.2014.
 */
@RequestScoped
public class VitoRepository {

//    public static ThreadLocal<DPCTRevisionHandler> threadLocal = new ThreadLocal() {};

    @Inject
    private EntityManager em;

//    @Inject
//    private DPCTRevisionHandler dpctRevisionHandler;


//    @PostConstruct
//    public void init(){
//        threadLocal.set(dpctRevisionHandler);
//    }

    public Vito create(Vito t) {
        em.getTransaction().begin();
        t.setChangedBy(Constants.SYSTEM_USER);
        t.setChangedOn(Calendar.getInstance().getTime());
        t.setChangedType(ChangeType.I);
        t.setLocked(Constants.UNLOCKED);
        em.persist(t);
        em.flush();
        em.getTransaction().commit();
        return t;
    }

    public Vito findById(Long id){
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Vito> criteria  = builder.createQuery(Vito.class);
        Root<Vito> from = criteria.from(Vito.class);
        criteria.where(builder.equal(from.get("id"), id));
        TypedQuery<Vito> query = em.createQuery(criteria);
        return query.getSingleResult();
    }

    public List<Vito> findAll() {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Vito> criteria  = builder.createQuery(Vito.class);
        Root<Vito> from = criteria.from(Vito.class);
        TypedQuery<Vito> query = em.createQuery(criteria);
        return query.getResultList();
    }

    public void merge(Vito versioned) {
        em.getTransaction().begin();
        em.merge(versioned);
        em.getTransaction().commit();
    }
}
